#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
'''
Created on 2016年6月1日

@author: zhaoxiang
'''

import sys,os,collections
sys.path.append('/home/hadoop/udf_data/python/user_track')
os.environ['PYTHON_EGG_CACHE'] = '/tmp/hadoop/.python-eggs/'
os.environ['PYTHON_EGG_DIR']='/tmp/hadoop/.python-eggs/'
import gua
from DB import DB
import ConfigParser
reload(sys)
sys.setdefaultencoding("utf-8")

conf = ConfigParser.ConfigParser() 
conf.read("config_sql.cfg")
    
detail_map=collections.defaultdict(dict)
outputPattern="\t".join(["%s"]*11)
collection_sep="\002"
k_v_pattern="%s\003%s"
########################################################################################
#web,mobile折扣日志处理
#rowSet=[user_id, unique_id, ugc_type, ugc_content,platform, ip, lon, lat, client_id,'',channel]
########################################################################################
class z_action(object):
    def __init__(self) :
        self.qyer_db = DB(gua.conn_qyer['host'], gua.conn_qyer['username'], gua.conn_qyer['password'], gua.conn_qyer['db'], gua.conn_qyer["port"])
        self.ra_db = DB(gua.conn_ra['host'], gua.conn_ra['username'], gua.conn_ra['password'], gua.conn_ra['db'], gua.conn_ra["port"])
#         self.plan_db = DB(gua.conn_plan["host"], gua.conn_plan["username"], gua.conn_plan["password"], gua.conn_plan["db"], gua.conn_plan["port"])
#         self.main_db = DB(gua.conn_main["host"], gua.conn_main["username"], gua.conn_main["password"], gua.conn_main["db"])
#         self.taiwan_set = self.get_taiwan()
        self.city_urlname = {}
        self.country_urlname = {}
        self.init_city_country_poi()
        self.guide_urlname = {}
        self.lm_ptype_urlname = {}
        self.lm_dept_urlname = {}
        self.lm_travel_urlname = {}
        
    def init_city_country_poi(self) :
        self.city_map = collections.defaultdict(str);
        self.country_map = collections.defaultdict(str);
        self.poi_map = collections.defaultdict(str);
        self.qyer_db.execute(conf.get("basic", "city"))
        result_set = self.qyer_db.fetchall()
        for result in result_set :
            self.city_map[str(result["id"])] = result["cityname"]
            
        self.qyer_db.execute(conf.get("basic", "country"))
        result_set = self.qyer_db.fetchall()
        for result in result_set :
            self.country_map[str(result["id"])] = result["catename"]
            
        self.qyer_db.execute(conf.get("basic", "poi"))
        result_set = self.qyer_db.fetchall()
        for result in result_set :
            if result["chinesename"]:
                self.poi_map[str(result["id"])] = result["chinesename"]            
    
    def __del__(self) :
        self.qyer_db.close()
#         self.plan_db.close()
        self.ra_db.close()
    
    def extract_z_action(self, rowSet) :
        #没登录过的，在web和m端的，过滤掉(app端有设备ID，所以不过滤)        
        #解析ugc类型和内容(id)
        channel= rowSet[10]
        ugc_type = rowSet[2]
        ugc_content = rowSet[3]
        
        parsed_type=None
        parsed_content=None
        lm_detail=""
#首页
        if ugc_type == "index" or ugc_type == "mindex" :
            parsed_type = "index"
            parsed_content = "-"
#折扣
        elif ugc_type == "z_detail" or ugc_type == "mz_detail" :
            if ugc_content.isdigit() :
                lm_id = int(ugc_content)
                parsed_type = "view_z_detail"
                parsed_content = lm_id
                lm_detail= self.z_detail(parsed_content)
        elif ugc_type == "z_zt" or ugc_type == "mz_zt" :
            parsed_type = "view_z_zt"
            parsed_content = ugc_content if ugc_content else "-"
        elif ugc_type == "mz_chose" or ugc_type =="z_chose" :
            parsed_type = "z_chose"
            parsed_content = ugc_content if ugc_content else "-"
        elif ugc_type == "z_index" or ugc_type=="mz_index" :
            parsed_type = "view_z_index"
            parsed_content = ugc_content if ugc_content else "-"
        elif ugc_type=="z_search":
            parsed_type="z_search"
            parsed_content= ugc_content if ugc_content else "-"
            lm_detail= k_v_pattern % ("keyword", parsed_content)
#目的地
        elif ugc_type == "place_index" or ugc_type=="mplace_index" :
            channel="place"
            parsed_type = "place_index"
            parsed_content = ugc_content if ugc_content else "-"
        elif ugc_type == "place_country" or ugc_type=="mplace_country" :
            channel="place"
            parsed_type = "place_country"
            parsed_content = ugc_content if ugc_content else "-"
            if ugc_content.isdigit() :
                lm_detail = (k_v_pattern + collection_sep + k_v_pattern) % ("id", ugc_content,"name",self.country_map[ugc_content])
        elif ugc_type == "place_city" or ugc_type=="mplace_city" :
            channel="place"
            parsed_type = "place_city"
            parsed_content = ugc_content if ugc_content else "-"
            if ugc_content.isdigit() :
                lm_detail = (k_v_pattern + collection_sep + k_v_pattern) % ("id", ugc_content,"name",self.city_map[ugc_content])
        elif ugc_type == "place_poi" or ugc_type=="mplace_poi" :
            channel="place"
            parsed_type = "place_poi"
            parsed_content = ugc_content if ugc_content else "-"
            if ugc_content.isdigit() :
                lm_detail = (k_v_pattern + collection_sep + k_v_pattern) % ("id", ugc_content,"name",self.poi_map[ugc_content])
        elif ugc_type == "place_mguide" or ugc_type=="mplace_mguide" :
            channel="place"
            parsed_type = "place_mguide"
            parsed_content = ugc_content if ugc_content else "-"
            if ugc_content.isdigit():
                lm_detail = k_v_pattern % ("mguide_id",ugc_content)
#锦囊
        elif ugc_type == "guide_index" :
            channel="guide"
            parsed_type = "guide_index"
            parsed_content = ugc_content if ugc_content else "-"            
        elif ugc_type == "guide_detail" :
            if ugc_content.isdigit() :
                channel="guide"
                parsed_type = "guide_detail"
                parsed_content = ugc_content
                lm_detail = self.jn_detail(parsed_content)
#plan行程
#         elif ugc_type == "plan_index" or ugc_type=="mplan_index" :
#             channel="plan"
#             parsed_type = "plan_index"
#             parsed_content = ugc_content if ugc_content else "-"
#         elif ugc_type == "plan_trip" or ugc_type=="mplan_trip" :
#             channel="plan"
#         elif ugc_type == "mplan_create" or ugc_type=="mmplan_create" :
#             channel="plan"
#             parsed_type = "mmplan_create"
#             parsed_content = ugc_content if ugc_content else "-"
#         elif ugc_type == "plan_edit" or ugc_type=="mplan_edit" :
#             channel="plan"
#             parsed_type = "plan_edit"
#             parsed_content = ugc_content if ugc_content else "-"
#             if ugc_content.isdigit():
#                 lm_detail = k_v_pattern % ("plan_id",ugc_content)
# #bbs（论坛）
#         elif ugc_type == "bbs_index" or ugc_type=="mbbs_index" :
#             channel="bbs"
#             parsed_type = "bbs_index"
#             parsed_content = ugc_content if ugc_content else "-"               
# #ask（问答）
#         elif ugc_type == "ask_index" or ugc_type=="mask_index" :
#             channel="ask"
#             parsed_type = "ask_index"
#             parsed_content = ugc_content if ugc_content else "-"
#         elif ugc_type == "ask_question" or ugc_type=="mask_question" :
#             channel="ask"
#             parsed_type = "ask_question"
#             parsed_content = ugc_content if ugc_content else "-"
#             if ugc_content.isdigit():
#                 lm_detail = k_v_pattern % ("question_id",ugc_content)
#         elif ugc_type == "ask_editquestion":
#             channel="ask"
#             parsed_type = "ask_editquestion"
#             parsed_content = ugc_content if ugc_content else "-"
#             if ugc_content.isdigit():
#                 lm_detail = k_v_pattern % ("question_id",ugc_content)
#         elif ugc_type == "ask_search":
#             channel="ask"
#             parsed_type = "ask_search"
#             parsed_content = ugc_content if ugc_content else "-" 
#             lm_detail = k_v_pattern % ("keyword",ugc_content)           
#         elif ugc_type == "ask_tags":
#             channel="ask"
#             parsed_type = "ask_tags"
#             parsed_content = ugc_content if ugc_content else "-"           
#             lm_detail = k_v_pattern % ("tag_word",ugc_content)
        if parsed_type and parsed_content:
            rowSet[2]= parsed_type
            rowSet[3]= parsed_content
            rowSet[9]= lm_detail.replace("\n", "").replace("\r", "")
            rowSet[10]= channel
            print outputPattern % tuple(rowSet)
   
    #折扣相关信息 
    def z_detail(self, x_id) :
        detail_info=detail_map["z"].get(x_id)
        if not detail_info:
            self.qyer_db.execute(conf.get("z", "z_detail"), (x_id,))
            res = self.qyer_db.fetchone()
            if res :
                tmp = [ k_v_pattern % (k,v if v is not None else "") for (k,v) in res.iteritems() ]
                detail_info = collection_sep.join(tmp)
                detail_map["z"][x_id]=detail_info
        return detail_info if detail_info else "";
         
           
    #锦囊相关信息 
    def jn_detail(self, x_id) :
        detail_info=detail_map["jn"].get(x_id)
        if not detail_info:
            self.qyer_db.execute(conf.get("jn", "jn_detail"), (x_id,))
            res = self.qyer_db.fetchone()
            if res :
                tmp = [ k_v_pattern % (k,v if v is not None else "") for (k,v) in res.iteritems() ]
                detail_info = collection_sep.join(tmp)
                detail_map["jn"][x_id]=detail_info
        return detail_info if detail_info else "";


    #折扣专题相关信息 
#     def lm_topic(self, ztid) :
#         self.qyer_db.execute("select id as zt_id,countryid,cityid from qyer_lastminute.lastminute_topic where id = %s", (ztid,))
#         lm_res = self.qyer_db.fetchone()
#         if lm_res :
#             tmp = [ k_v_pattern % (k,v if v is not None else "") for (k,v) in lm_res.iteritems() ]
#             return collection_sep.join(tmp)

if __name__ == '__main__':
    obj = z_action()
    for line in sys.stdin:
        rowSet = line.strip().split('\t')
        if (len(rowSet) != 11):
            continue
        obj.extract_z_action(rowSet)